package pl.edu.mimuw.irs.rcp.view.figure;


import org.eclipse.draw2d.AbstractConnectionAnchor;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;

/**
 * @author Jakub Rauch
 * Created on: 2009-05-26
 * 
 * Class mostly copied from http://markmail.org/message/67zopouxx66le37y 
 * (original org.eclipse.draw2d uses getOwner().getBounds() instead of getBox()) 
 */
public class EllipseAnchor extends AbstractConnectionAnchor {

	/** Constructor for EllipseAnchor. */
	public EllipseAnchor() {
	}

	/** Constructor for EllipseAnchor. 
	 * @param owner */
	public EllipseAnchor(IFigure owner) {
		super(owner);
	}

	/** @see org.eclipse.draw2d.ConnectionAnchor#getLocation(Point) */
	public Point getLocation(Point reference) {

		Rectangle r = Rectangle.SINGLETON;
		Rectangle box = getBox();
		r.setBounds(new Rectangle(box.x, box.y, box.width + 1, box.height + 1)); // Trick to straighten arcs
		r.translate(-1, -1);
		r.resize(1, 1);
		getOwner().translateToAbsolute(r);

		Point ref = r.getCenter().negate().translate(reference);

		if (ref.x == 0)
			return new Point(reference.x, (ref.y > 0) ? r.bottom() : r.y);
		if (ref.y == 0)
			return new Point((ref.x > 0) ? r.right() : r.x, reference.y);

		float dx = (ref.x > 0) ? 0.5f : -0.5f;
		float dy = (ref.y > 0) ? 0.5f : -0.5f;

		// ref.x, ref.y, r.width, r.height != 0 => safe to proceed

		float k = (float) (ref.y * r.width) / (ref.x * r.height);
		k = k * k;

		return r.getCenter().translate((int) (r.width * dx / Math.sqrt(1 + k)),
				(int) (r.height * dy / Math.sqrt(1 + 1 / k)));
	}

	protected Rectangle getBox() {
		return getOwner().getBounds();
	}

	/**
	 * Returns the anchor's reference point. In the case of the EllipseAnchor,
	 * this is the center of the anchor's owner.
	 * 
	 * @return The reference point
	 */
	public Point getReferencePoint() {
		if (getOwner() == null)
			return null;
		else {
			Point ref = getBox().getCenter();
			getOwner().translateToAbsolute(ref);
			return ref;
		}
	}
}
